package com.hghivln.utils;


import com.hghivln.pojo.domain.SimpleUser;
import com.hghivln.pojo.domain.User;
import com.hghivln.pojo.vo.ActiverUser;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.subject.support.DefaultSubjectContext;

/**
 * Shiro相关工具类  获取当前登录的用户
 * 切换身份 ， 动态修改subject的用户属性
 */
public class ShiroUtils {

    public static User getLoginUser() {
        Session session = SecurityUtils.getSubject().getSession();
        SimplePrincipalCollection principalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
        if (principalCollection == null) {
            return null;
        }
        return (User) principalCollection.getPrimaryPrincipal();
    }

    /**
     * 得到当前登陆的用户对象的ActiveUser
     */
    public static ActiverUser getActiverUser() {
        Subject subject = SecurityUtils.getSubject();
        return  (ActiverUser) subject.getPrincipal();
    }

    /**
     * 得到当前登录用户的对象User
     */
    public static User getCurrentUser() {
        return getActiverUser().getUser();
    }

    /**
     * 得到当前登录用户的对象SimpleUser
     */
    public static SimpleUser getCurrentSimpleUser() {
        User user = getActiverUser().getUser();
        return new SimpleUser(user.getUserId(),user.getUserName());
    }
}
